<template>
  <div class="bg">
    <div class="container-m" style="padding-top: 0.01rem; padding-bottom: 0.2rem">
      <!-- <div class="search">
        <el-form>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item>
                <el-select v-model="serviceId" clearable filterable :placeholder="$t('选择_搜索服务')">
                  <el-option-group class="no-divider" v-for="group in serviceList" :key="group.parent"
                    :label="group.parent">
                    <el-option v-for="item in group.options" :key="item.serviceId" :label="item.label"
                      :value="item.serviceId" style="width: 3rem" />
                  </el-option-group>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item>
                <el-select v-model="selectStatus" clearable :placeholder="$t('选择状态')">
                  <el-option v-for="item in statsOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item>
                <el-input type="textarea" :autosize="{ minRows: 6, maxRows: 6 }" :placeholder="$t('一行一个')"
                  v-model="imeis" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="search-btn">
          <div class="btn">
            <img src="@/assets/images/export_icon_03.png" alt="" />
            <span @click="exportOrders">{{ $t('导出订单') }}</span>
          </div>
          <div class="btn" @click="searchByPcForm">
            <div>{{ $t('搜索订单') }}</div>
          </div>
        </div> -->

      <!-- <el-button type="primary" @click="search" style="width: 100%">{{ $t('搜索') }}</el-button> -->
      <!-- </div> -->
      <div class="block" style="
          padding: 10px 0;
          background-color: #fff;
          margin-top: 0.1rem;
          box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        ">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50, 200]" :page-size="pageSize" :total="total" layout="prev, total,next, jumper"
          style="text-align: center">
          <span>{{ currentPage }}</span>
        </el-pagination>
      </div>
      <div class="list">
        <div class="total">
          {{ $t('总共为您找到') }} <span style="color: red">{{ total }}</span> {{ $t('条账单数据') }}
        </div>
        <div class="item" v-for="(item, index) in orderList" :key="index" ref="imgBox">
          <div class="p">
            {{ $t('订单id') }}：{{ item.service_id }} {{ item.payNum }}
          </div>
          <div class="p">
            {{ $t('充值方式') }}：
            <template>
              <el-tag v-if="item.payWay == 'ALI_QR'" size="mini">{{
                $t("支付宝")
              }}</el-tag>
              <el-tag type="success" size="mini" v-else>{{ $t("微信") }}</el-tag>
            </template>
          </div>
          <div class="p">{{ $t('充值金额') }}：{{ item.payAmount }}</div>
          <div class="p">{{ $t('充值结果') }}：
            <template>
              <el-tag type="success" v-if="item.payResult == 1" size="mini">{{
                $t("成功")
              }}</el-tag>
              <el-tag type="danger" size="mini" v-else>{{ $t("失败") }}</el-tag>
            </template>
          </div>
          <div class="p">{{ $t('创建时间') }}：{{ formatDateTime(new Date(item.createTime)) }}</div>
        </div>
        <div v-if="orderList.length === 0" style="color: #666; padding: 20px; text-align: center">
          {{ $t('暂无数据') }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import apiService from "@/api/apiService";
import {
  fetchAllData,
  isMobile, formatDateTime
} from "@/utils";
import * as XLSX from "xlsx";
import * as util from "@/utils/index";

export default {
  name: "OrderLog",
  data() {
    return {
      stateType: {
        0: "",
        1: "info",
        2: "success",
        3: "warning",
        4: "danger",
      },
      serviceList: [],
      serviceId: "",
      selectStatus: "",
      imeis: "",
      result: "",
      orderByMap: {},
      orderByKey: "",
      orderList: [],
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      createTimeDu: [],
      updateTimeDu: [],
      searchRequest: {},
      selectedRows: [],
      exportCount: 0,
      selectOptionWidth: "",
      statsOptions: [],
      centerDialogVisible: false,
      src: "",
      showNecessaryElement: false,
    };
  },
  computed: {
    mobile() {
      return isMobile();
    },
  },
  mounted() {
    // const { apResult } = this.$route.query;
    // if (apResult !== undefined) {
    //   this.selectStatus = Number(apResult);
    // }
    // this.getService();
    // this.initSearchRequest();
    // this.initOrderByList();
    this.initOrderList();
    // this.statsOptions = util.getStatsOptions();
  },

  components: {
  },
  methods: {
    formatDateTime,
    countByPcForm() {
      let request = this.initSearchRequestByForm();
      this.$nextTick(function () {
        apiService.post("/order-count", request).then((res) => {
          let pageCount = Math.ceil(res.data / this.pageSize);
          this.$notify({
            title: "计数完成",
            message: `共${res.data}个订单符合筛选条件，${pageCount}页`,
            type: "success",
            position: "bottom-right",
          });
        });
      });
    },


    /* 页大小变了依旧用之前的请求, 从第一页开始查 */
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.searchRequest.page = this.currentPage;
      this.searchRequest.pageSize = val;
      this.doSearch(this.searchRequest);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.searchRequest.page = val;
      this.doSearch_0(this.searchRequest, false);
    },
    exportOrders() {
      let request = this.initSearchRequestByForm();
      fetchAllData("/order-list", request)
        .then((result) => {
          this.exportList(result);
        })
        .catch((error) => {
          console.log(error);
          this.$message.error(this.$t('导出订单失败'));
        });
    },
    exportList(arr) {
      console.log(arr);
      let tableData = [
        [
          "订单编号",
          "服务名称",
          "状态",
          "IMEI/SN",
          "反馈结果",
          "提交时间",
          "更新时间",
          "使用积分",
          "备注",
        ],
      ]; // 表格表头
      arr.forEach((item) => {
        let rowData = [];
        //导出内容的字段
        rowData = [
          item.id,
          "#" + item.service_id + " " + item.service_theme,
          util.stateMapping(item.ap_result),
          item.imei,
          item.result
            ?.replace(/<br>/g, "\n")
            .replace(/<("[^"]*"|'[^']*'|[^'">])*>/g, " "),
          item.create_time,
          item.update_time,
          item.price,
          item.desc,
        ];
        tableData.push(rowData);
      });
      let workSheet = XLSX.utils.aoa_to_sheet(tableData);
      let bookNew = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(bookNew, workSheet, `Results`); // 工作簿名称
      let timeStr = util.formatDateTime(new Date());
      let name = `OrderHistory ${timeStr}.xlsx`;
      XLSX.writeFile(bookNew, name); // 保存的文件名
    },

    doSearch_0() {
      apiService
        .post("/paylog-list", {
          pageNumber: this.currentPage,
          pageSize: this.pageSize,
          // ...this.form
        })
        .then((res) => {
          this.orderList = res.data.records;
          this.total = res.data.total;
        });
    },
    initOrderByList() {
      let orderFields = [
        {
          field: "create_time",
          cname: "创建时间",
        },
        {
          field: "update_time",
          cname: "更新时间",
        },
        {
          field: "price",
          cname: "订单金额",
        },
      ];
      let orderBys = [
        {
          order: "desc",
          cname: "降序",
        },
        {
          order: "asc",
          cname: "升序",
        },
      ];
      orderFields.forEach((f) => {
        orderBys.forEach((b) => {
          this.orderByMap[f.cname + b.cname] = {
            orderFiled: f.field,
            orderBy: b.order,
          };
        });
      });
    },
    initOrderList() {
      if (JSON.stringify(this.$route.query) !== "{}") {
        console.log("orderlog");
        console.log(this.$route.query);
        this.searchRequest = this.$route.query;
      }
      this.doSearch_0(this.searchRequest, false);
    },



  },
};
</script>

<style lang="scss" scoped>
.list {
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  margin-top: 0.1rem;
  border-radius: 8px;
  padding: 0.1rem;

  .total {
    font-size: 0.16rem;
    color: #333;
    text-align: center;
    border-bottom: 1px solid #eee;
    padding-bottom: 0.05rem;
  }

  .item {
    padding: 10px 0;
    border-bottom: 1px solid #eee;

    .p {
      font-size: 0.14rem;
      color: #666;
      line-height: 1.8;
    }
  }
}

.search {
  padding-top: 0.2rem;
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 0.1rem;
  border-radius: 8px;

  .search-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.1rem;

    .btn {
      display: flex;
      align-items: center;
      justify-content: center;
      background-image: linear-gradient(to right, #7c93f5, #5381f5);
      flex: 1;
      height: 0.4rem;
      border-radius: 10px;
      color: #fff;
      font-size: 0.14rem;

      img {
        width: 0.14rem;
        margin-right: 10px;
      }
    }
  }
}

.bg {
  background-color: #f4f4f4;
  min-height: 100vh;
}
</style>
